﻿using Dapper;
using System;
using BCEntity.Trading.SaleContractReceiptRecord;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.SaleContractReceiptRecord
{
    /// <summary>
    /// 销售合同收款记录
    /// </summary>
    public class SaleContractReceiptRecordData : ISaleContractReceiptRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM salecontractreceiptrecord";
        private const string QUERY = @"SELECT SaleContractReceiptRecordId,SaleContractId,SaleContractNo,PaymentTime,PaymentRecordId,PaymentChannel,PaymentAmount,CreateTime FROM salecontractreceiptrecord";
        public SaleContractReceiptRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查销售合同收款记录是否存在
        public async Task<bool> Exists(long saleContractReceiptRecordId)
        {
            string sql = string.Format(@"{0} WHERE SaleContractReceiptRecordId=?SaleContractReceiptRecordId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleContractReceiptRecordId", saleContractReceiptRecordId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加销售合同收款记录
        public async Task<SaleContractReceiptRecordEntity> Add(SaleContractReceiptRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("salecontractreceiptrecord", new string[] { "SaleContractId", "SaleContractNo", "PaymentTime", "PaymentRecordId", "PaymentChannel", "PaymentAmount" });
            sql = string.Format("{0} {1} WHERE SaleContractReceiptRecordId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleContractId", entity.SaleContractId, DbType.Int64, size: 20);
            parameters.Add("?SaleContractNo", entity.SaleContractNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PaymentTime", entity.PaymentTime, DbType.DateTime);
            parameters.Add("?PaymentRecordId", entity.PaymentRecordId, DbType.Int64, size: 20);
            parameters.Add("?PaymentChannel", entity.PaymentChannel?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?PaymentAmount", entity.PaymentAmount, DbType.Decimal, size: 10);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleContractReceiptRecordEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改销售合同收款记录
        public async Task<SaleContractReceiptRecordEntity> Update(SaleContractReceiptRecordEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("salecontractreceiptrecord", new string[] { "SaleContractId", "SaleContractNo", "PaymentTime", "PaymentRecordId", "PaymentChannel", "PaymentAmount" }, new string[] { "SaleContractReceiptRecordId" });
            sql = string.Format("{0} {1} WHERE SaleContractReceiptRecordId=?SaleContractReceiptRecordId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleContractReceiptRecordId", entity.SaleContractReceiptRecordId, DbType.Int64, size: 20);
            parameters.Add("?SaleContractId", entity.SaleContractId, DbType.Int64, size: 20);
            parameters.Add("?SaleContractNo", entity.SaleContractNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PaymentTime", entity.PaymentTime, DbType.DateTime);
            parameters.Add("?PaymentRecordId", entity.PaymentRecordId, DbType.Int64, size: 20);
            parameters.Add("?PaymentChannel", entity.PaymentChannel?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?PaymentAmount", entity.PaymentAmount, DbType.Decimal, size: 10);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleContractReceiptRecordEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除销售合同收款记录
        public async Task<bool> Delete(long saleContractReceiptRecordId)
        {
            string sql = @"DELETE FROM salecontractreceiptrecord WHERE SaleContractReceiptRecordId=?SaleContractReceiptRecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleContractReceiptRecordId", saleContractReceiptRecordId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取销售合同收款记录
        public async Task<SaleContractReceiptRecordEntity> GetEntity(long saleContractReceiptRecordId)
        {
            string sql = string.Format(@"{0} WHERE SaleContractReceiptRecordId=?SaleContractReceiptRecordId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleContractReceiptRecordId", saleContractReceiptRecordId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SaleContractReceiptRecordEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售合同收款记录列表
        public async Task<IEnumerable<SaleContractReceiptRecordEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<SaleContractReceiptRecordEntity>(QUERY);
        }
        #endregion

        #region 获取销售合同收款记录分页
        public async Task<(IEnumerable<SaleContractReceiptRecordEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM salecontractreceiptrecord {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<SaleContractReceiptRecordEntity, int>(sql, parameters);
        }
        #endregion
    }
}



